package com.framework.auth.service.impl;

import com.framework.authorization.vo.UserDetailsVo;
import com.framework.common.Enums.FrameworkErrorCodeEnum;
import com.framework.common.Enums.UserTypeEnum;
import com.framework.core.api.feign.RemoteApiService;
import com.framework.core.api.feign.RemoteThirdUserService;
import com.framework.core.api.response.ThirdUserInfoQueryRes;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhoubb
 * @version V1.0
 * @Date 2020/4/12 17:16
 * @since JDK 1.8
 */
@Service("userDetailsService")
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private RemoteApiService remoteApiService;

    @Autowired
    private RemoteThirdUserService remoteThirdUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询第三方平台用户信息
        ThirdUserInfoQueryRes thirdUserInfo = remoteThirdUserService.getThirdUserInfoByOpenId(username);
        if(thirdUserInfo == null || !StringUtils.equals(FrameworkErrorCodeEnum.SUCCESS.getCode(), thirdUserInfo.getCode())) {
            log.warn("[用户认证]-[微信用户信息查询失败]-[{}]", thirdUserInfo == null? "网络问题":thirdUserInfo.getMsg());
            throw new DisabledException(username);
        }
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(1);
        authorities.add(new SimpleGrantedAuthority(UserTypeEnum.getCode(Integer.valueOf(thirdUserInfo.getUserType()))));
        UserDetails userDetails = new UserDetailsVo(thirdUserInfo.getOldUserId(), thirdUserInfo.getOpenId(), authorities);
        return userDetails;
    }
}
